import Vue from 'vue'
import Vuex from 'vuex'
import { loginIn } from '../api/channel'

Vue.use(Vuex)

export default new Vuex.Store({
  // strict: true,
  state: {
    token: window.localStorage.getItem('token') || '',
    refresh_token: window.localStorage.getItem('refresh_token') || '',
    pinglunlengths: null, // 文章的评论条数
    searchOfhistory: JSON.parse(window.localStorage.getItem('searchOfhistory')) || [],
    userinfo: JSON.parse(window.localStorage.getItem('userinfo')) || {},
  },
  mutations: {
    // 保存token
    settoken (state, payload) {
      state.token = payload
      window.localStorage.setItem('token', state.token)
    },
    // 保存refresh_token
    setrefreshtokens (state, payload) {
      state.refresh_token = payload
      window.localStorage.setItem('refresh_token', state.refresh_token)
    },
    // 记录每篇文章发表的评论条数
    change (state, payload) {
      state.pinglunlengths = payload
    },
    // 保存搜索历史记录
    setsearchOfhistory (state, payload) {
      // 如果这次的搜索历史和之前的历史记录中重复就不添加,每一项都不重复就添加进去
      const res = state.searchOfhistory.every(ele => {
        return ele.content !== payload.content
      })
      if (res) {
        state.searchOfhistory.push(payload)
      }
      window.localStorage.setItem('searchOfhistory', JSON.stringify(state.searchOfhistory))
    },
    // 删除搜索历史记录
    deletesearchOfhistory (state, payload) {
      state.searchOfhistory = []
      window.localStorage.setItem('searchOfhistory', JSON.stringify(state.searchOfhistory))
    },
    // 删除某一条历史记录
    deleteonesearchOfhistory (state, payload) {
      state.searchOfhistory.splice(payload, 1)
      window.localStorage.setItem('searchOfhistory', JSON.stringify(state.searchOfhistory))
    },
    // 保存用户信息
    setuserinfo (state, payload) {
      state.userinfo = payload
      window.localStorage.setItem('userinfo', JSON.stringify(state.userinfo))
    },
    // 设置用户名称
    setuserinfoname (state, payload) {
      state.userinfo.name = payload
      window.localStorage.setItem('userinfo', JSON.stringify(state.userinfo))
    },
    // 设置用户头像
    setuserinfophoto (state, payload) {
      state.userinfo.photo = payload
      window.localStorage.setItem('userinfo', JSON.stringify(state.userinfo))
    }
  },
  actions: {
    async asyncLoginActions (store, payload) {
      const res = await loginIn(payload)
      const { token, refresh_token } = res.data.data
      store.commit('settoken', token)
      store.commit('setrefreshtokens', refresh_token)
    }
  },
  modules: {
  }
})
